﻿Imports System.Runtime.CompilerServices
Imports System.Text
Imports System.Globalization

Module Extensions

	<Extension()>
	Public Function UnicodeToASCII(UnicodeString As String) As String
		'If String.IsNullOrEmpty(UnicodeString) Then
		'	Return Nothing
		'Else

		'	Dim ASCII As Integer
		'	Dim myBytes As Byte()
		'	Dim EncodedChar As String
		'	Dim sb As New StringBuilder

		'	For i = 0 To UnicodeString.Length - 1
		'		ASCII = AscW(UnicodeString(i))
		'		If ASCII < 32 OrElse ASCII = 61 OrElse ASCII > 126 Then
		'			myBytes = Encoding.UTF8.GetBytes(UnicodeString(i))
		'			For Each myByte In myBytes
		'				EncodedChar = Hex(myByte).ToUpper
		'				If EncodedChar.Length = 1 Then
		'					EncodedChar = "0" & EncodedChar
		'				End If
		'				sb.Append("=" & EncodedChar)
		'			Next
		'		Else
		'			sb.Append(UnicodeString(i))
		'		End If
		'	Next

		'	Return sb.ToString

		Dim codePoint As String

		Dim returnString As New StringBuilder

		Dim ee = StringInfo.GetTextElementEnumerator(UnicodeString)

		While ee.MoveNext()
			Dim e As String = ee.GetTextElement()
			'this next line is to fix an e-sword processing issue with RTF commands encoded using Unicode characters
			'e-sword doesn't know what to do if there are multiple directives in a single verse
			'it only obey's the first directive if they are all encoded as Unicode
			'another change was made to just render all ASCII characters as they are
			'because ASCII-7 and UTF-8 are the same for the first 127 characters
			'If Not "{\scaps }".Contains(e) Then
			If Not " !""#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~".Contains(e) Then
				codePoint = Char.ConvertToUtf32(e, 0)
				returnString.Append(String.Format("\u{0}?", codePoint))
			Else
				returnString.Append(e)
			End If
		End While

		Return returnString.ToString
	End Function
End Module
